package com.hkts.naturalgasauthentication.base.controller;

import com.hkts.management.common.utils.Result;
import com.hkts.management.common.utils.ResultUtil;
import com.hkts.naturalgasauthentication.base.entity.*;
import com.hkts.naturalgasauthentication.base.service.*;
import com.hkts.naturalgasauthentication.common.redis.RedisTemplateHelper;
import com.hkts.naturalgasauthentication.utils.PageUtil;
import com.hkts.naturalgasauthentication.utils.PageVo;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.*;

import java.util.Date;
import java.util.List;
import java.util.Set;


/**
 * @author Exrickx
 */
@Slf4j
@RestController
@RequestMapping("/authentication/role")
@Transactional
public class RoleController {

    @Autowired
    private RoleService roleService;

    @Autowired
    private UserRoleService userRoleService;

    @Autowired
    private RolePermissionService rolePermissionService;

    @Autowired
    private RoleDepartmentService roleDepartmentService;

    @Autowired
    private StringRedisTemplate redisTemplate;

    @Autowired
    private RedisTemplateHelper redisTemplateHelper;
    @Autowired
    private PermissionService permissionService;

    /**
     * 获取全部角色
     * @return
     */
    @RequestMapping(value = "/getAllList",method = RequestMethod.GET)
    public Result<Object> roleGetAll(){
        List<Role> list = roleService.getAll();
        return ResultUtil.data(list);
    }

    /**
     * 分页获取角色
     * @param page
     * @return
     */
    @RequestMapping(value = "/getAllByPage",method = RequestMethod.GET)
    public Result<Page<Role>> getRoleByPage(PageVo page){

        Page<Role> list = roleService.findAll(PageUtil.initPage(page));
        for(Role role : list.getContent()){
            // 角色拥有权限
            List<RolePermission> permissions = rolePermissionService.findByRoleId(role.getId());
            for(int i=0;i<permissions.size();i++){
                Permission permission = permissionService.get(permissions.get(i).getPermissionId());
                if(permission!=null){
                    permissions.get(i).setPermissionLevel(permission.getLevel());
                }
            }
            role.setPermissions(permissions);
            // 角色拥有数据权限
            List<RoleDepartment> departments = roleDepartmentService.findByRoleId(role.getId());
            role.setDepartments(departments);
        }
        return new ResultUtil<Page<Role>>().setData(list);
    }

    /**
     * 设置或取消默认角色
     * @param id
     * @param isDefault
     * @return
     */
    @RequestMapping(value = "/setDefault",method = RequestMethod.POST)
    public Result<Object> setDefault(@RequestParam String id,
                                     @RequestParam Boolean isDefault){

        Role role = roleService.get(id);
        if(role==null){
            return ResultUtil.error("角色不存在");
        }
        List<Role> byDefaultRole = roleService.findByDefaultRole(true);
        for (Role role1 : byDefaultRole) {
            role1.setDefaultRole(false);
        }
        role.setDefaultRole(isDefault);
        roleService.update(role);
        return ResultUtil.success("设置成功");
    }

    /**
     * 编辑角色分配菜单权限
     * @param roleId
     * @param permIds
     * @return
     */
    @RequestMapping(value = "/editRolePerm",method = RequestMethod.POST)
    public Result<Object> editRolePerm(String roleId,
                                        String permIds){
        String[] array = permIds.split(",");
        //删除其关联权限
        rolePermissionService.deleteByRoleId(roleId);
        //分配新权限
        for(String permId : array){
            RolePermission rolePermission = new RolePermission();
            rolePermission.setRoleId(roleId);
            rolePermission.setPermissionId(permId);
            rolePermissionService.save(rolePermission);
        }
        //手动批量删除缓存
        /*Set<String> keysUser = redisTemplateHelper.keys("user:" + "*");
        redisTemplate.delete(keysUser);
        Set<String> keysUserRole = redisTemplateHelper.keys("userRole:" + "*");
        redisTemplate.delete(keysUserRole);
        Set<String> keysUserPerm = redisTemplateHelper.keys("userPermission:" + "*");
        redisTemplate.delete(keysUserPerm);
        Set<String> keysUserMenu = redisTemplateHelper.keys("permission::userMenuList:*");
        redisTemplate.delete(keysUserMenu);*/
        return ResultUtil.data(null);
    }

    /**
     * 编辑角色分配数据权限
     * @param roleId
     * @param dataType
     * @param depIds
     * @return
     */
    @RequestMapping(value = "/editRoleDep",method = RequestMethod.POST)
    public Result<Object> editRoleDep(@RequestParam String roleId,
                                      @RequestParam Integer dataType,
                                      @RequestParam(required = false) String[] depIds){

        Role r = roleService.get(roleId);
        r.setDataType(dataType);
        roleService.update(r);
        // 删除其关联数据权限
        roleDepartmentService.deleteByRoleId(roleId);
        // 分配新数据权限
        for(String depId : depIds){
            RoleDepartment roleDepartment = new RoleDepartment();
            roleDepartment.setRoleId(roleId);
            roleDepartment.setDepartmentId(depId);
            roleDepartmentService.save(roleDepartment);
        }
        // 手动删除相关缓存
        /*Set<String> keys = redisTemplateHelper.keys("department:" + "*");
        redisTemplate.delete(keys);
        Set<String> keysUserRole = redisTemplateHelper.keys("userRole:" + "*");
        redisTemplate.delete(keysUserRole);*/

        return ResultUtil.data(null);
    }

    /**
     * 保存数据
     * @param role
     * @return
     */
    @RequestMapping(value = "/save",method = RequestMethod.POST)
    public Result<Role> save(Role role){
        role.setDefaultRole(false);
        Role r = roleService.save(role);
        return new ResultUtil<Role>().setData(r);
    }

    /**
     * 更新数据
     * @param entity
     * @return
     */
    @RequestMapping(value = "/edit",method = RequestMethod.POST)
    public Result<Role> edit(Role entity){

        Role role = roleService.get(entity.getId());
        if (role != null){
            Date createTime = role.getCreateTime();
            role.setCreateTime(createTime);
            role.setName(entity.getName());
            role.setDescription(entity.getDescription());
        }

        //手动批量删除缓存
        /*Set<String> keysUser = redisTemplateHelper.keys("user:" + "*");
        redisTemplate.delete(keysUser);
        Set<String> keysUserRole = redisTemplateHelper.keys("userRole:" + "*");
        redisTemplate.delete(keysUserRole);*/
        return new ResultUtil<Role>().setData(role);
    }

    /**
     * 批量通过ids删除
     * @param ids
     * @return
     */
    @RequestMapping(value = "/delAllByIds/{ids}",method = RequestMethod.DELETE)
    public Result<Object> delByIds(@PathVariable String[] ids){


        for(String id:ids){
            List<UserRole> list = userRoleService.findByRoleId(id);
            if(list!=null&&list.size()>0){
                return ResultUtil.error("删除失败，包含正被用户使用关联的角色");
            }
        }
        for(String id:ids){
            roleService.delete(id);
            //删除关联菜单权限
            rolePermissionService.deleteByRoleId(id);
            //删除关联数据权限
            roleDepartmentService.deleteByRoleId(id);
        }
        return ResultUtil.success("删除成功");
    }

}
